package io.elegant.sessions

import io.elegant.*
import android.content.Context
import com.google.protobuf.Any
import io.grpc.stub.StreamObserver
import java.io.File

class FileSession(
    stub: ElegantApiGrpc.ElegantApiStub,
    private val context: Context
) : BaseSession(stub, context) {
    override val sendStreamObserver: StreamObserver<Elegant.Interaction> = stub.file(receiveStreamObserver)
    private var filename: String = ""
    private var file: File? = null

    override suspend fun onDestroy(throwable: Throwable?) {
        super.onDestroy(throwable)
        file = null
    }

    override suspend fun onReceive(name: String, sessionId: Long, futureId: Long, vararg argv: Any) {
        when (name) {
            "open" -> open(*argv)
            "read" -> read(sessionId, futureId)
            "readLine" -> readLine(sessionId, futureId)
            "write" -> write(*argv)
            "exists" -> exists(sessionId, futureId)
            "remove" -> remove()

            else -> super.onReceive(name, sessionId, futureId, *argv)
        }
    }

    private fun open(vararg argv: Any) {
        filename = argv[0].toStringValue()
//        val mode = argv[1].toStringValue()
        file = File(context.filesDir, filename)
    }

    private fun read(sessionId: Long, futureId: Long) {
        if (file == null) {
            file = File(context.filesDir, filename)
        }
        val data = file!!.readText()
        this.sendAction("onRead", sessionId, futureId, data.toAny())
    }

    private fun readLine(sessionId: Long, futureId: Long) {
        val line = file?.readLines()
        if (line != null) {
            this.sendAction("onRead", sessionId, futureId, line[0].toAny())
        }
    }

    private fun write(vararg argv: Any) {
        file?.writeText(argv[0].toStringValue())
    }

    private fun exists(sessionId: Long, futureId: Long) {
        sendAction("onExists", sessionId, futureId, file?.isFile.toAny())
    }

    private fun remove() {
        file?.delete()
    }
}